<?php
// +----------------------------------------------------------------------
// | 迁于首页
// +----------------------------------------------------------------------
// | Author: cart <469714167@qq.com>
// +----------------------------------------------------------------------
// | Datetime: 2018-5-16 14:59:00
// +----------------------------------------------------------------------
// | Copyright: 创讯科技
// +----------------------------------------------------------------------
namespace app\wx\controller;
use think\Loader;
class Login extends Init
{
    // private $IndexModel;
    /**
     * [_initialize 初始化]
     * @return [type] [description]
     * @author carl
     * @version 2018-02-05
     * @copyright wei liang
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->UserModel = Loader::model('User');
    }

    public function onlogin(){
        $code = input('get.code');
        $appid= 'wxa20052cca5271e47';
        $secret= 'e66c2c6abc2502832a62e4bbb3e708d6';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $authname = 'wechat_session_key'.$appid;
        $result = http_get($url);
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || isset($json['errcode'])) {
                $errCode = $json['errcode'];
                $errMsg = $json['errmsg'];
                return false;
            }
            $session_key = $json['session_key'];
            $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
            $userInfo = $this->UserModel->getUserInfo($json['openid']);
            if(!$userInfo){
                $this->UserModel->openid = $json['openid'];
                $this->UserModel->save();
            }
            parent::setCache($authname,$session_key,$expire);
            return $json;
        }
        return false;
    }
}